RaidSearcher = CreateFrame('Frame')
RaidSearcher:RegisterEvent("CHAT_MSG_CHANNEL");



SLASH_RAIDSEARCHER1, SLASH_RAIDSEARCHER2 = '/rs', '/raidsearcher';
function SlashCmdList.RAIDSEARCHER(msg, editbox)

	if ( RaidSearcherFrame:IsShown() ) then
		HideUIPanel(RaidSearcherFrame);
 	else
    ShowUIPanel(RaidSearcherFrame);
  end

end


function RaidSearcher:addchatmessage(i_name, i_msg)
	local samemsg=false;
	local raidsuche=false;
	local chat_msg={};
	local found_match={};	


	if RaidSearcher.chat[i_name] == nil then
		chat_msg = { name = i_name, msg= {i_msg}, change=time(), update=time(), raid=false	}
		RaidSearcher.chat[i_name] = chat_msg;
	end
	
	
		for msg_key, msg_text in ipairs(RaidSearcher.chat[i_name].msg) do
			if i_msg == msg_text then
				samemsg = true;
			end
			
			
			for word in string.gmatch(msg_text, "%w+") do
				word = string.lower(word);
				found_match[word] = (found_match[word] or 0)  + 1;
			end	
		
		end
	

		local raid_keys = {	
			"icc", "lfm", "pdk", "pdc", "maly", "icc10", "icc25", "pdok"
		}
		
		local noraid_keys = {	
			"lfg"
		}		

		for _, word in ipairs(raid_keys) do
				if found_match[word] then
					raidsuche = true;
				end
		end
		for _, word in ipairs(noraid_keys) do
				if found_match[word] then
					raidsuche = false;
				end
		end		
	
		if (RaidSearcher.chat[i_name].change - 60) > RaidSearcher.chat[i_name].update then
			RaidSearcher.chat[i_name].change = time();
		end

		if raidsuche then
			RaidSearcher.chat[i_name].raid = true;		
		end

		if not samemsg then
			chat_msg = RaidSearcher.chat[i_name];
			RaidSearcher.chat[i_name].change=time();
			table.insert(chat_msg.msg, i_msg);
			if # chat_msg.msg > 10 then
				table.remove(chat_msg.msg, 1);
			end
	
			RaidSearcher.chat[i_name] = chat_msg;
		end

		RaidSearcher.chat[i_name].update = time();
end

function RaidSearcher:Sort()

	wipe(RaidSearcher.raids);
	for index, value in pairs (RaidSearcher.chat) do
		if value.raid then
			tinsert(RaidSearcher.raids, value);	
		end
	end
	table.sort(RaidSearcher.raids, function(a,b) return a.change>b.change end)


end

function RaidSearcher:OnEvent(event, ...)

	if event == "CHAT_MSG_CHANNEL" then
	local message, author, language, channelwithnumber, target, flags, zoneID, channelnumber, channelname  = ...;
		if channelnumber == 2 then
			RaidSearcher:addchatmessage(author, message);
		end
	end


	RaidSearcher:Sort();
	RaidSearcherFrameChats_Update()

end


RaidSearcher.chat = {}
RaidSearcher.raids = {}

RaidSearcher:SetScript("OnEvent", RaidSearcher.OnEvent )